package com.example.petstore.controller;

import com.example.petstore.common.CommonResponse;
import com.example.petstore.domain.Admin;
import com.example.petstore.domain.MessageLog;
import com.example.petstore.domain.User;
import com.example.petstore.service.AdminService;
import com.example.petstore.service.MessageService;
import com.example.petstore.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import java.time.LocalDateTime;

@Controller
@SessionAttributes({"loginUser","loginAdmin"})
public class ChatController {
    @Autowired
    private MessageService messageService;
    @Autowired
    private UserService userService;
    @Autowired
    private AdminService adminService;

    @GetMapping("/user/getMessage")
    @ResponseBody
    public CommonResponse userGetMessage(ModelMap model) {
        User user = (User) model.getAttribute("loginUser");
        return messageService.getMessagesByUser(user.getUsername());
    }

    @GetMapping("/admin/closeChat")
    @ResponseBody
    public CommonResponse adminCloseChat(@RequestParam("customerId") String username, Model model) {
        System.out.println("sushuh");
        Admin admin = (Admin) model.getAttribute("loginAdmin");
        System.out.println(admin);
        if (admin != null) {
            MessageLog messageLog = new MessageLog();
            messageLog.setAdminname(admin.getAdminname());
            messageLog.setAdminLeftTime(LocalDateTime.now());
            messageLog.setUsername(username);
            return messageService.updateMessageLogForAdmin(username,admin.getAdminname(),messageLog);
        } else {
            return CommonResponse.creatForError();
        }
    }

    @GetMapping("/user/closeChat")
    @ResponseBody
    public CommonResponse userCloseChat(ModelMap model) {
        User user = (User) model.getAttribute("loginUser");
        if (user != null) {
            MessageLog messageLog = new MessageLog();
            messageLog.setUserLeftTime(LocalDateTime.now());
            messageLog.setUsername(user.getUsername());

            return messageService.updateMessageLogForUser(user.getUsername(), messageLog);

        } else {
            return CommonResponse.creatForError();
        }
    }
}